package org.spring.order.module.domain.order.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.spring.client.ItemClient;
import org.spring.client.ItemVO;
import org.spring.client.UserClient;
import org.spring.client.UserVO;
import org.spring.order.module.domain.order.vo.OrderVO;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderService {
    private final UserClient userClient;
    private final ItemClient itemClient;
    private final Map<Long, OrderVO> orderMap = new ConcurrentHashMap<>();


    public String create(Long userId, Long itemId) {

        UserVO userVO = userClient.queryUserById(userId);

        ItemVO itemVO = itemClient.queryUserById(itemId);

        if (userVO.getMoney() < itemVO.getItemPrice()) {
            return userVO.getUsername() + "太穷了，买不起" + itemVO.getItemName();
        }

        // 创建订单，持久化到数据库中
        OrderVO orderVO = new OrderVO(userId, itemId);
        save(orderVO);


        ResponseEntity<Void> response = userClient.pay(userId, itemVO.getItemPrice());
        log.info("response: {}", response);

        if (!response.getStatusCode().is2xxSuccessful()) {
            return "请求失败 => 扣款失败";
        }

        return userVO.getUsername() + "下单" + itemVO.getItemName();

    }

    private void save(OrderVO orderVO) {
        orderMap.put(orderVO.getOrderId(), orderVO);
    }
}
